<template>
	<view class="explore-page">
		<!-- 顶部搜索栏 -->
		<view class="search-header">
			<view class="search-input-box">
				<view class="city-selector-part" @click="goToCitySelect">
					<text class="city-name">{{ currentCity }}</text>
					<text class="city-arrow">▼</text>
				</view>
				<text class="divider">|</text>
				<view class="search-part" @click="goToSearch">
					<text class="search-icon">🔍</text>
					<text class="search-placeholder">{{ searchPlaceholder }}</text>
				</view>
			</view>
			<view class="map23" @click="goToMap">
				<image src="/static/nav-3.png" mode="" style="width: 37px; height: 37px;"></image>
			</view>
		</view>

		<!-- 筛选栏 -->
		<view class="filter-bar">
			<view class="filter-item" :class="{ active: currentFilter === 'area' }" @click="toggleFilter('area')">
				<text class="filter-text">区域</text>
				<text class="filter-arrow">▼</text>
			</view>
			<view class="filter-item" :class="{ active: currentFilter === 'type' }" @click="toggleFilter('type')">
				<text class="filter-text">方式</text>
				<text class="filter-arrow">▼</text>
			</view>
			<view class="filter-item" :class="{ active: currentFilter === 'price' }" @click="toggleFilter('price')">
				<text class="filter-text">价格</text>
				<text class="filter-arrow">▼</text>
			</view>
			<view class="filter-item" :class="{ active: currentFilter === 'more' }" @click="toggleFilter('more')">
				<text class="filter-text">筛选</text>
				<text class="filter-arrow">▼</text>
			</view>
		</view>

		<!-- 筛选下拉面板（区域、方式、价格） -->
		<view class="filter-dropdown" v-if="showFilterPanel && currentFilter !== 'more'">
			<!-- 区域筛选 -->
			<view v-if="currentFilter === 'area'" class="area-filter-wrapper">
				<view class="area-filter-content">
					<!-- 左侧分类列 -->
					<scroll-view scroll-y class="area-category-list">
						<view v-for="(category, index) in areaCategories" :key="index" class="category-item"
							:class="{ active: currentCategoryIndex === index }" @click="selectCategory(index)">
							{{ category.label }}
						</view>
					</scroll-view>

					<!-- 中间子分类列 -->
					<scroll-view scroll-y class="area-subcategory-list">
						<view v-for="(sub, index) in currentSubCategories" :key="index" class="subcategory-item"
							:class="{ active: currentSubCategoryIndex === index }" @click="selectSubCategory(index)">
							{{ sub.label }}
						</view>
					</scroll-view>

					<!-- 右侧区域列表 -->
					<scroll-view scroll-y class="area-list">
						<view v-for="(area, index) in currentAreas" :key="index" class="area-item"
							:class="{ selected: tempSelectedArea.label === area.label }"
							@click="tempSelectedArea = { label: area.label, value: area.value }">
							{{ area.label }}
						</view>
					</scroll-view>
				</view>

				<!-- 底部按钮 -->
				<view class="filter-buttons">
					<view class="cancel-btn" @click="cancelAreaFilter">取消</view>
					<view class="confirm-btn" @click="confirmAreaFilter">确定</view>
				</view>
			</view>

			<!-- 方式筛选 -->
			<view v-if="currentFilter === 'type'" class="type-filter-wrapper">
				<view class="type-picker-container">
					<!-- 中间指示线 -->
					<view class="picker-indicator">
						<view class="indicator-line top-line"></view>
						<view class="indicator-line bottom-line"></view>
					</view>

					<!-- 滚动列表 -->
					<scroll-view scroll-y class="type-picker-scroll" @scroll="onTypeScroll">
						<!-- 顶部占位 -->
						<view class="picker-placeholder"></view>

						<!-- 选项列表 -->
						<view v-for="(item, index) in typeOptions" :key="index" :id="'type-item-' + index"
							class="picker-item" :class="{
                                'picker-selected': currentTypeIndex === index,
                                'picker-near': Math.abs(currentTypeIndex - index) === 1
                            }" @click="selectTypeByIndex(index)">
							{{ item }}
						</view>

						<!-- 底部占位 -->
						<view class="picker-placeholder"></view>
					</scroll-view>
				</view>

				<view class="filter-buttons">
					<view class="cancel-btn" @click="cancelTypeFilter">取消</view>
					<view class="confirm-btn" @click="confirmTypeFilter">确定</view>
				</view>
			</view>

			<!-- 价格筛选 -->
			<view v-if="currentFilter === 'price'" class="price-filter-wrapper">
				<view class="price-picker-container">
					<!-- 中间指示线 -->
					<view class="picker-indicator">
						<view class="indicator-line top-line"></view>
						<view class="indicator-line bottom-line"></view>
					</view>

					<!-- 滚动列表 -->
					<scroll-view scroll-y class="price-picker-scroll" @scroll="onPriceScroll">
						<!-- 顶部占位 -->
						<view class="picker-placeholder"></view>

						<!-- 选项列表 -->
						<view v-for="(item, index) in priceOptions" :key="index" :id="'price-item-' + index"
							class="picker-item" :class="{
                                'picker-selected': currentPriceIndex === index,
                                'picker-near': Math.abs(currentPriceIndex - index) === 1
                            }" @click="selectPriceByIndex(index)">
							{{ item }}
						</view>

						<!-- 底部占位 -->
						<view class="picker-placeholder"></view>
					</scroll-view>
				</view>

				<view class="filter-buttons">
					<view class="cancel-btn" @click="cancelPriceFilter">取消</view>
					<view class="confirm-btn" @click="confirmPriceFilter">确定</view>
				</view>
			</view>
		</view>

		<!-- 筛选右侧弹框（仅更多筛选） -->
		<view class="filter-modal" v-if="showFilterPanel && currentFilter === 'more'">
			<!-- 更多筛选 -->
			<view v-if="currentFilter === 'more'" class="more-filter-wrapper">
				<scroll-view scroll-y class="more-filter-scroll">
					<view class="more-filter-title">更多选项</view>

					<!-- 户型 -->
					<view class="filter-group">
						<view class="group-title">户型</view>
						<view class="group-options">
							<view v-for="(item, index) in moreFilters.roomType" :key="index" class="option-item"
								:class="{ 'option-selected': selectedMoreFilters.roomType.includes(item) }"
								@click="toggleMoreFilter('roomType', item)">
								{{ item }}
							</view>
						</view>
					</view>

					<!-- 楼层 -->
					<view class="filter-group">
						<view class="group-title">楼层</view>
						<view class="group-options">
							<view v-for="(item, index) in moreFilters.floor" :key="index" class="option-item"
								:class="{ 'option-selected': selectedMoreFilters.floor.includes(item) }"
								@click="toggleMoreFilter('floor', item)">
								{{ item }}
							</view>
						</view>
					</view>

					<!-- 朝向 -->
					<view class="filter-group">
						<view class="group-title">朝向</view>
						<view class="group-options">
							<view v-for="(item, index) in moreFilters.orientation" :key="index" class="option-item"
								:class="{ 'option-selected': selectedMoreFilters.orientation.includes(item) }"
								@click="toggleMoreFilter('orientation', item)">
								{{ item }}
							</view>
						</view>
					</view>

					<!-- 特色 -->
					<view class="filter-group">
						<view class="group-title">特色</view>
						<view class="group-options">
							<view v-for="(item, index) in moreFilters.characteristic" :key="index" class="option-item"
								:class="{ 'option-selected': selectedMoreFilters.characteristic.includes(item) }"
								@click="toggleMoreFilter('characteristic', item)">
								{{ item }}
							</view>
						</view>
					</view>
				</scroll-view>

				<!-- 底部按钮 -->
				<view class="filter-buttons">
					<view class="cancel-btn" @click="clearMoreFilter">清除</view>
					<view class="confirm-btn" @click="confirmMoreFilter">确定</view>
				</view>
			</view>
		</view>

		<!-- 遮罩层（仅更多筛选时显示） -->
		<view class="mask" v-if="showFilterPanel && currentFilter === 'more'" @click="closeFilter"></view>

		<!-- 房源列表 -->
		<view class="house-list">
			<view v-for="(house, index) in filteredHouseList" :key="index" class="house-card"
				@click="goToDetail(house)">
				<image :src="'http://localhost:8080' + house.houseImg" class="house-image" mode="aspectFill"></image>
				<view class="house-info">
					<view class="house-title">{{ house.title }}</view>
					<view class="house-desc">{{ house.desc }}</view>
					<view class="house-tags">
						<text v-for="(tag, idx) in house.tags" :key="idx" class="tag">
							{{ tag }}
						</text>
					</view>
					<view class="house-footer">
						<view class="house-price">
							<text class="price-num">{{house.price }}</text>
							<text class="price-unit">元/月</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 空状态 -->
			<view v-if="filteredHouseList.length === 0" class="empty-state">
				<text class="empty-icon">🏠</text>
				<text class="empty-text">暂无符合条件的房源</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				currentCity: '大连',
				currentCityId: 'AREA_2bc437ca-b3d2-5c3c', // 默认城市ID
				currentFilter: '', // area, type, price, more
				showFilterPanel: false,
				communityName: '', // 从搜索小区页面接收的小区名称
				communityId: '', // 从搜索小区页面接收的小区ID
				searchPlaceholder: '请输入小区或地址', // 动态更新的搜索占位符

				// 筛选选项
				typeOptions: ['不限', '整租', '合租'],
				priceOptions: ['不限', '1000及以下', '1000 - 2000', '2000 - 3000', '3000 - 4000', '4000 - 5000', '5000 - 7000',
					'7000以上'
				],
				roomOptions: ['不限', '一居室', '二居室', '三居室', '四居室及以上'],

				// 更多筛选选项
				moreFilters: {
					roomType: ['一室', '二室', '三室', '四室', '四室+'],
					floor: ['高楼层', '中楼层', '低楼层'],
					orientation: ['东', '西', '南', '北', '东南', '东北', '西南', '西北'],
					characteristic: ['集中供暖', '双卫生间', '近地铁', '随时看房', '精装', '公寓', '独立卫生间', '押一付一', '独立阳台', '月租', '限女生',
						'限男生', '新上'
					]
				},

				// 选中的更多筛选
				selectedMoreFilters: {
					roomType: [],
					floor: [],
					orientation: [],
					characteristic: []
				},

				// 区域数据
		areaCategories: [], // 区域分类（区域、地铁等）
		currentCategoryIndex: 0, // 当前选中的分类索引
		currentSubCategoryIndex: 0, // 当前选中的子分类索引
		tempSelectedArea: { label: '不限', value: '' }, // 临时选中的区域（包含名称和ID）
		// 搜索列表数据
		searchlist: [],

		// 已选筛选项
		selectedArea: { label: '不限', value: '' },
				selectedType: '不限',
				selectedPrice: '不限',
				selectedRoom: '不限',

				// 临时选择（用于确定前）
				tempSelectedType: '不限', // 临时选中的方式
				currentTypeIndex: 0, // 当前滚动到的方式索引
				tempSelectedPrice: '不限',
				currentPriceIndex: 0, // 当前滚动到的价格索引
			}
		},
		onLoad(options) {
				// 接收从首页传递过来的城市信息
				if (options.city && options.cityId) {
					this.currentCity = options.city;
					this.currentCityId = options.cityId;
				}

				// 监听城市选择（同时支持selectCity和citySelected事件，确保与首页同步）
				uni.$on('selectCity', (city) => {
					this.currentCity = city.label || city.name;
					this.currentCityId = city.value || city.id;
					// 城市变化时重新获取房源数据和筛选条件
				this.getData();
				this.loadAreaData();
				});
				uni.$on('citySelected', (city) => {
					this.currentCity = city.label || city.name;
					this.currentCityId = city.value || city.id;
					// 城市变化时重新获取房源数据和筛选条件
			this.getData();
			this.loadAreaData();
				});

			// 监听从sous.vue页面传递过来的小区参数（通过全局事件）
			uni.$on('selectCommunity', (communityData) => {
				this.communityName = communityData.communityName;
				this.communityId = communityData.communityId || '';
				console.log('接收到的小区信息:', this.communityName, this.communityId);
				// 更新搜索占位符显示选中的小区
				this.searchPlaceholder = this.communityName;
				// 触发数据刷新
			this.getData();
			});

			// 加载区域数据
			this.loadAreaData();
			// 列表
			this.getData();
		},
		onUnload() {
			uni.$off('selectCity');
			uni.$off('citySelected');
			uni.$off('selectCommunity');
		},
		computed: {
			// 当前子分类列表
			currentSubCategories() {
				if (this.areaCategories.length === 0) return [];
				return this.areaCategories[this.currentCategoryIndex]?.children || [];
			},

			// 当前区域列表：新增“不限”选项（不修改原有逻辑，仅添加）
		currentAreas() {
			if (this.currentSubCategories.length === 0) return [{ label: '不限', value: '' }]; // 无数据时显示“不限”
			const areas = this.currentSubCategories[this.currentSubCategoryIndex]?.children || [];
			return [{ label: '不限', value: '' }, ...areas]; // 有数据时在顶部添加“不限”
		},

			// 筛选后的房源列表（添加前端价格筛选作为后备）
		filteredHouseList() {
			// 先进行小区名称筛选
			let filtered = this.searchlist;
			
			if (this.communityName && !this.communityId) {
				filtered = filtered.filter(house =>
					(house.title && house.title.includes(this.communityName)) ||
					(house.desc && house.desc.includes(this.communityName))
				);
			}
			
			// 再进行价格筛选（前端后备筛选，确保即使后端没处理也能生效）
			if (this.selectedPrice !== '不限') {
				let priceRange = this.selectedPrice;
				if (priceRange.includes('及以下')) {
					// 提取数字部分，如"1000及以下"提取1000
					let match = priceRange.match(/\d+/);
					if (match) {
						const maxPrice = parseInt(match[0]);
						filtered = filtered.filter(house => {
							const price = house.price?.toString() || '';
							const priceMatch = price.match(/\d+/);
							if (!priceMatch) return false;
							const housePrice = parseInt(priceMatch[0]);
							return housePrice <= maxPrice;
						});
					}
				} else if (priceRange.includes('以上')) {
					// 提取数字部分，如"7000以上"提取7000
					let match = priceRange.match(/\d+/);
					if (match) {
						const minPrice = parseInt(match[0]);
						filtered = filtered.filter(house => {
							const price = house.price?.toString() || '';
							const priceMatch = price.match(/\d+/);
							if (!priceMatch) return false;
							const housePrice = parseInt(priceMatch[0]);
							return housePrice >= minPrice;
						});
					}
				} else if (priceRange.includes('-')) {
					// 提取两个数字，如"1000 - 2000"提取1000和2000
					let matches = priceRange.match(/\d+/g);
					if (matches && matches.length >= 2) {
						const minPrice = parseInt(matches[0]);
						const maxPrice = parseInt(matches[1]);
						filtered = filtered.filter(house => {
							const price = house.price?.toString() || '';
							const priceMatch = price.match(/\d+/);
							if (!priceMatch) return false;
							const housePrice = parseInt(priceMatch[0]);
							return housePrice >= minPrice && housePrice <= maxPrice;
						});
					}
				}
			}
			
			// 再进行区域筛选（前端后备筛选，确保即使后端没处理也能生效）
			if (this.selectedArea.value) {
				filtered = filtered.filter(house => {
					// 检查房源的areaId或area字段是否匹配选中的区域ID
					return house.areaId === this.selectedArea.value || 
						   house.area?.id === this.selectedArea.value ||
						   // 也检查区域名称，以防数据结构不同
						   house.area?.name === this.selectedArea.label;
				});
			}
			
			// 再进行更多筛选条件（户型、楼层、朝向、特色）的前端筛选
			// 户型筛选
			if (this.selectedMoreFilters.roomType.length > 0) {
				filtered = filtered.filter(house => {
					// 从title或desc中判断户型
					const text = (house.title || '') + (house.desc || '');
					return this.selectedMoreFilters.roomType.some(type => {
						// 处理"四室+"的情况
						if (type === '四室+') {
							return text.includes('四室') || text.includes('五室') || text.includes('六室') || text.includes('多室') ||
								   text.includes('四居室') || text.includes('五居室') || text.includes('六居室') || text.includes('多居室');
						} else {
							// 同时匹配"一室"和"一居室"格式
							const typeWithJu = type + '居';
							return text.includes(type) || text.includes(typeWithJu);
						}
					});
				});
			}
			
			// 楼层筛选
			if (this.selectedMoreFilters.floor.length > 0) {
				filtered = filtered.filter(house => {
					const text = (house.title || '') + (house.desc || '') + (house.floor || '');
					return this.selectedMoreFilters.floor.some(floor => text.includes(floor));
				});
			}
			
			// 朝向筛选
			if (this.selectedMoreFilters.orientation.length > 0) {
				filtered = filtered.filter(house => {
					// 只检查房源的orientation字段，避免小区名等非朝向信息干扰
					const orientationText = house.orientation || '';
					// 获取选中的朝向
					const selectedOrientations = this.selectedMoreFilters.orientation;
					
					// 处理朝向匹配逻辑，只要满足其中一个选中的朝向条件即可
					return selectedOrientations.some(selectedOrient => {
						// 如果选中的是单个朝向（如"东"、"西"等）
						if (selectedOrient.length === 1) {
							// 检查房源朝向中是否包含该朝向
							return orientationText.includes(selectedOrient);
						} else {
							// 如果选中的是组合朝向（如"东南"、"西南"等）
							// 检查房源朝向中是否包含组合朝向，或者包含组合朝向中的所有单个朝向
							return orientationText.includes(selectedOrient) || 
								   selectedOrient.split('').every(dir => orientationText.includes(dir));
						}
					});
				});
			}
			
			// 特色筛选
			if (this.selectedMoreFilters.characteristic.length > 0) {
				filtered = filtered.filter(house => {
					const text = (house.title || '') + (house.desc || '') + (house.tags || []).join('');
					return this.selectedMoreFilters.characteristic.some(char => text.includes(char));
				});
			}
			
			return filtered;
		}
		},
		methods: {
			// 加载区域数据
			async loadAreaData() {
				try {
					const res = await uni.request({
						url: 'http://localhost:8080/houses/condition',
						method: 'GET',
						data: {
							id: this.currentCityId
						}
					});

					console.log('区域数据完整返回:', res);

					if (res.statusCode === 200) {
						let data = res.data.body || res.data.data || res.data;

						console.log('原始完整数据:', data);

						// 从返回的数据中提取区域相关的分类
						const categories = [];

						// 添加区域分类
						if (data.area) {
							console.log('区域数据:', data.area);
							categories.push(data.area);
						}

						// 添加地铁分类（可能的字段名：subway, metro, subwayLine等）
						if (data.subway) {
							console.log('地铁数据:', data.subway);
							categories.push(data.subway);
						} else if (data.metro) {
							console.log('地铁数据:', data.metro);
							categories.push(data.metro);
						} else if (data.subwayLine) {
							console.log('地铁数据:', data.subwayLine);
							categories.push(data.subwayLine);
						}

						this.areaCategories = categories;

						console.log('处理后的区域分类:', this.areaCategories);
						console.log('分类数量:', this.areaCategories.length);
					}
				} catch (error) {
					console.error('加载区域数据失败:', error);
				}
			},
			// 获取列表数据
		async getData() {
			// 构建筛选参数
			let params = {
				cityId: this.currentCityId
			};

			// 添加小区筛选
			if (this.communityName && this.communityId) {
				params.communityId = this.communityId;
			}

			// 添加区域筛选
			if (this.selectedArea.value) {
				params.areaId = this.selectedArea.value;
			}

			// 添加租赁方式筛选
			if (this.selectedType !== '不限') {
				params.rentType = this.selectedType; // 使用字符串'整租'或'合租'，而不是布尔值
				console.log('租赁方式:', params.rentType);
			}

			// 添加价格筛选
			console.log('开始价格筛选，当前selectedPrice:', this.selectedPrice);
			if (this.selectedPrice !== '不限') {
				// 根据价格选项设置对应的值
				let priceRange = this.selectedPrice;
				console.log('价格范围:', priceRange);
				if (priceRange.includes('及以下')) {
					// 提取数字部分，如"1000及以下"提取1000
					let match = priceRange.match(/\d+/);
					if (match) {
						params.maxPrice = parseInt(match[0]);
						console.log('maxPrice:', params.maxPrice);
					}
				} else if (priceRange.includes('以上')) {
					// 提取数字部分，如"7000以上"提取7000
					let match = priceRange.match(/\d+/);
					if (match) {
						params.minPrice = parseInt(match[0]);
						console.log('minPrice:', params.minPrice);
					}
				} else if (priceRange.includes('-')) {
					// 提取两个数字，如"1000 - 2000"提取1000和2000
					let matches = priceRange.match(/\d+/g);
					if (matches && matches.length >= 2) {
						params.minPrice = parseInt(matches[0]);
						params.maxPrice = parseInt(matches[1]);
						console.log('minPrice:', params.minPrice, 'maxPrice:', params.maxPrice);
					}
				}
			} else {
				// 如果选择不限，确保不传递价格参数
				delete params.minPrice;
				delete params.maxPrice;
				console.log('选择不限，删除价格参数');
			}
			console.log('价格筛选完成，params:', params);

			// 添加更多筛选条件
			if (this.selectedMoreFilters.roomType.length > 0) {
				params.roomType = this.selectedMoreFilters.roomType;
			}
			if (this.selectedMoreFilters.floor.length > 0) {
				params.floor = this.selectedMoreFilters.floor;
			}
			if (this.selectedMoreFilters.orientation.length > 0) {
				params.orientation = this.selectedMoreFilters.orientation;
			}
			if (this.selectedMoreFilters.characteristic.length > 0) {
				params.characteristic = this.selectedMoreFilters.characteristic;
			}

			// 发送请求获取筛选后的数据
		try {
			// 构建完整URL，将筛选参数添加到查询字符串中
			let url = 'http://localhost:8080/houses';
			let queryParams = Object.entries(params)
				.map(([key, value]) => {
					// 处理数组类型的参数
					if (Array.isArray(value)) {
						return value.map(v => `${encodeURIComponent(key)}=${encodeURIComponent(v)}`).join('&');
					} else {
						return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
					}
				})
				.join('&');
			
			if (queryParams) {
				url += '?' + queryParams;
			}
			
			console.log("请求URL:", url);
			
			const res = await uni.request({
				url: url,
				method: 'GET'
			});
			
			console.log("筛选参数:", params);
			console.log("响应数据:", res.data);
			console.log("响应数据长度:", res.data.body?.list?.length);
			// 打印第一条房源数据的完整结构，查看区域字段
			if (res.data.body?.list?.length > 0) {
				console.log("第一条房源数据结构:", JSON.stringify(res.data.body.list[0], null, 2));
			}
			
			// 显示价格范围内的房源数量
			if (params.minPrice || params.maxPrice) {
				const min = params.minPrice || 0;
				const max = params.maxPrice || Infinity;
				const filteredByPrice = res.data.body?.list?.filter(house => {
					// 从价格字符串中提取数字，如"2500元/月"提取2500
					const price = house.price?.toString() || '';
					const priceMatch = price.match(/\d+/);
					if (!priceMatch) return false;
					const housePrice = parseInt(priceMatch[0]);
					return housePrice >= min && housePrice <= max;
				}) || [];
				console.log(`${min}-${max}范围内的房源数量:`, filteredByPrice.length);
			}
			
			this.searchlist = res.data.body?.list || [];
			console.log('searchlist设置后的数据长度:', this.searchlist.length);
		} catch (error) {
			console.error('获取房源数据失败:', error);
			uni.showToast({
				title: '获取房源数据失败',
				icon: 'none'
			});
		}
		},
			// 选择左侧分类
			selectCategory(index) {
				this.currentCategoryIndex = index;
				this.currentSubCategoryIndex = 0; // 重置子分类索引
			},

			// 选择中间子分类
			selectSubCategory(index) {
				this.currentSubCategoryIndex = index;
			},

			// 取消区域筛选
			cancelAreaFilter() {
				this.tempSelectedArea = this.selectedArea;
				this.closeFilter();
			},

			// 确定区域筛选（选择不限时重置）
	confirmAreaFilter() {
		this.selectedArea = this.tempSelectedArea;
		this.closeFilter();
		console.log('选择区域:', this.selectedArea);

		uni.showToast({
			title: '已选择: ' + this.selectedArea.label,
			icon: 'none'
		});
		
		// 重新获取筛选后的数据
			this.getData();
	},

			// 切换筛选面板
			toggleFilter(type) {
				if (this.currentFilter === type) {
					this.showFilterPanel = false;
					this.currentFilter = '';
				} else {
					this.currentFilter = type;
					this.showFilterPanel = true;

					// 如果打开价格筛选，初始化临时选择
					if (type === 'price') {
						this.tempSelectedPrice = this.selectedPrice;
						const index = this.priceOptions.indexOf(this.selectedPrice);
						this.currentPriceIndex = index >= 0 ? index : 0;
					}

					// 如果打开区域筛选，初始化临时选择
				if (type === 'area') {
					// 深拷贝，避免引用问题
					this.tempSelectedArea = JSON.parse(JSON.stringify(this.selectedArea));
					this.currentCategoryIndex = 0;
					this.currentSubCategoryIndex = 0;
				}

					// 如果打开方式筛选，初始化临时选择
					if (type === 'type') {
						this.tempSelectedType = this.selectedType;
						const index = this.typeOptions.indexOf(this.selectedType);
						this.currentTypeIndex = index >= 0 ? index : 0;
					}
				}
			},

			// 关闭筛选
			closeFilter() {
				this.showFilterPanel = false;
				this.currentFilter = '';
			},

			// 方式滚动事件
			onTypeScroll(e) {
				const scrollTop = e.detail.scrollTop;
				const systemInfo = uni.getSystemInfoSync();
				const screenWidth = systemInfo.screenWidth;
				const ratio = screenWidth / 750;
				const itemHeight = 70 * ratio;

				const index = Math.round(scrollTop / itemHeight);
				const newIndex = Math.max(0, Math.min(index, this.typeOptions.length - 1));

				if (this.currentTypeIndex !== newIndex) {
					this.currentTypeIndex = newIndex;
					this.tempSelectedType = this.typeOptions[newIndex];
				}
			},

			// 点击选择方式
			selectTypeByIndex(index) {
				this.currentTypeIndex = index;
				this.tempSelectedType = this.typeOptions[index];
			},

			// 取消方式筛选
			cancelTypeFilter() {
				this.tempSelectedType = this.selectedType;
				this.closeFilter();
			},

			// 确定方式筛选（选择不限时重置）
		confirmTypeFilter() {
			this.selectedType = this.tempSelectedType;
			this.closeFilter();
			console.log('选择方式:', this.selectedType);

			uni.showToast({
				title: '已选择: ' + this.selectedType,
				icon: 'none'
			});
			
			// 重新获取筛选后的数据
			this.getData();
		},

			// 价格滚动事件
			onPriceScroll(e) {
				const scrollTop = e.detail.scrollTop;
				// 将rpx转换为实际像素（以750设计稿为基准）
				const systemInfo = uni.getSystemInfoSync();
				const screenWidth = systemInfo.screenWidth;
				const ratio = screenWidth / 750;
				const itemHeight = 70 * ratio; // 每个选项的实际高度

				// 计算当前滚动到的索引（中间位置）
				const index = Math.round(scrollTop / itemHeight);
				const newIndex = Math.max(0, Math.min(index, this.priceOptions.length - 1));

				if (this.currentPriceIndex !== newIndex) {
					this.currentPriceIndex = newIndex;
					this.tempSelectedPrice = this.priceOptions[newIndex];
				}
			},

			// 点击选择价格
			selectPriceByIndex(index) {
				this.currentPriceIndex = index;
				this.tempSelectedPrice = this.priceOptions[index];
			},

			// 取消价格筛选
			cancelPriceFilter() {
				this.tempSelectedPrice = this.selectedPrice;
				this.closeFilter();
			},

			// 确定价格筛选（选择不限时重置）
		confirmPriceFilter() {
			this.selectedPrice = this.tempSelectedPrice;
			this.closeFilter();
			console.log('选择价格:', this.selectedPrice);

			uni.showToast({
				title: '已选择: ' + this.selectedPrice,
				icon: 'none'
			});
			
			// 重新获取筛选后的数据
			this.getData();
		},

			// 选择户型
			selectRoom(item) {
				this.selectedRoom = item;
				this.closeFilter();
				console.log('选择户型:', item);
			},

			// 切换更多筛选选项
			toggleMoreFilter(type, item) {
				const index = this.selectedMoreFilters[type].indexOf(item);
				if (index > -1) {
					// 已选中，取消选中
					this.selectedMoreFilters[type].splice(index, 1);
				} else {
					// 未选中，添加选中
					this.selectedMoreFilters[type].push(item);
				}
			},

			// 清除更多筛选（重置所有更多条件）
		clearMoreFilter() {
			this.selectedMoreFilters = {
				roomType: [],
				floor: [],
				orientation: [],
				characteristic: []
			};
			uni.showToast({
				title: '已清除更多筛选条件',
				icon: 'none'
			});
			
			// 重新获取筛选后的数据
			this.getData();
		},

			// 确定更多筛选
		confirmMoreFilter() {
			this.closeFilter();
			console.log('更多筛选:', this.selectedMoreFilters);

			// 统计选中的数量
			const count = Object.values(this.selectedMoreFilters).reduce((total, arr) => total + arr.length, 0);

			if (count > 0) {
				uni.showToast({
					title: `已选择 ${count} 个条件`,
					icon: 'none'
				});
			} else {
				uni.showToast({
					title: '未选择任何筛选条件',
					icon: 'none'
				});
			}
			
			// 重新获取筛选后的数据
			this.getData();
		},

			// 跳转到城市选择
			goToCitySelect() {
				uni.navigateTo({
					url: '/ulit/city/city'
				});
			},

			// 跳转到搜索
			goToSearch() {
				uni.navigateTo({
					url: '/ulit/detalisearch/detalisearch'
				});
			},

			// 跳转到我的
			goToMine() {
				uni.switchTab({
					url: '/pages/mine/mine'
				});
			},

			// 跳转到地图页面
			goToMap() {
				uni.navigateTo({
					url: '/ulit/ditu/ditu'
				});
			},

		  // 查看房源详情
        goToDetail(house) {
            console.log('查看房源:', house);
            // 传递房源ID和其他必要信息到详情页
            uni.navigateTo({
                url: `/ulit/detalispublish/detalispublish?houseId=${house.id || ''}&houseCode=${house.houseCode || ''}`
            });
        }
		    }
		}
</script>

<style scoped>
	.explore-page {
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	/* 顶部搜索栏 */
	.search-header {
		height: 45rpx;
		background-color: #fff;
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
		gap: 20rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	/* 搜索输入框 */
	.search-input-box {
		flex: 1;
		display: flex;
		align-items: center;
		background-color: #fff;
		padding: 0 30rpx;
		height: 80rpx;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	/* 城市选择器部分 */
	.city-selector-part {
		display: flex;
		align-items: center;
		padding-right: 15rpx;
	}

	.city-name {
		font-size: 30rpx;
		color: #333;
		font-weight: 500;
		margin-right: 8rpx;
	}

	.city-arrow {
		font-size: 20rpx;
		color: #666;
	}

	/* 分隔符 */
	.divider {
		font-size: 30rpx;
		color: #ddd;
		margin: 0 15rpx;
	}

	/* 搜索部分 */
	.search-part {
		flex: 1;
		display: flex;
		align-items: center;
	}

	.search-icon {
		font-size: 32rpx;
		margin-right: 15rpx;
	}

	.search-placeholder {
		font-size: 28rpx;
		color: #999;
	}

	/* 地图图标 */
	.map23 {
		width: 80rpx;
		height: 80rpx;
		
	}

	.map23 image {
		width: 100%;
		height: 100%;
		margin-top: 5px;
		margin-left: 5px;
	}

	/* 筛选栏 */
	.filter-bar {
		height: 92rpx;
		background-color: #fff;
		display: flex;
		align-items: center;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.filter-item {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
		position: relative;
	}

	.filter-item.active .filter-text {
		color: #00B386;
	}

	.filter-item.active .filter-arrow {
		color: #00B386;
		transform: rotate(180deg);
	}

	.filter-text {
		font-size: 30rpx;
		color: #333;
		margin-right: 8rpx;
	}

	.filter-arrow {
		font-size: 20rpx;
		color: #666;
		transition: transform 0.3s;
	}

	/* 筛选下拉面板（区域、方式、价格） */
	.filter-dropdown {
		background-color: #fff;
		z-index: 997;
		max-height: 600rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
		overflow: hidden;
	}

	/* 筛选右侧弹框（仅更多筛选） */
	.filter-modal {
		position: fixed;
		top: 180rpx;
		right: 0;
		bottom: 0;
		width: 66.66%;
		background-color: #fff;
		z-index: 997;
		box-shadow: -4rpx 0 20rpx rgba(0, 0, 0, 0.1);
		overflow: hidden;
	}

	.filter-list {
		max-height: 600rpx;
	}

	/* 方式筛选专属样式 */
	.type-filter-wrapper {
		display: flex;
		flex-direction: column;
		height: 100%;
	}

	.type-picker-container {
		position: relative;
		height: 480rpx;
		overflow: hidden;
	}

	.type-picker-scroll {
		height: 100%;
		width: 100%;
	}

	/* 区域筛选专属样式 */
	.area-filter-wrapper {
		display: flex;
		flex-direction: column;
		height: 100%;
	}

	.area-filter-content {
		display: flex;
		flex: 1;
		overflow: hidden;
	}

	/* 左侧分类列 */
	.area-category-list {
		width: 160rpx;
		background-color: #f8f8f8;
		max-height: 480rpx;
	}

	.category-item {
		padding: 30rpx 20rpx;
		text-align: center;
		font-size: 28rpx;
		color: #666;
		background-color: #f8f8f8;
	}

	.category-item.active {
		background-color: #fff;
		color: #333;
		font-weight: 500;
	}

	/* 中间子分类列 */
	.area-subcategory-list {
		flex: 1;
		background-color: #fff;
		max-height: 480rpx;
		border-right: 1rpx solid #f0f0f0;
	}

	.subcategory-item {
		padding: 30rpx 30rpx;
		font-size: 30rpx;
		color: #666;
	}

	.subcategory-item.active {
		color: #000;
		font-weight: bold;
	}

	/* 右侧区域列表 */
	.area-list {
		flex: 1;
		background-color: #fff;
		max-height: 480rpx;
	}

	.area-item {
		padding: 30rpx 30rpx;
		font-size: 30rpx;
		color: #666;
	}

	.area-item.selected {
		color: #000;
		font-weight: bold;
	}

	.filter-option {
		padding: 35rpx 30rpx;
		font-size: 32rpx;
		color: #ccc;
		text-align: center;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.filter-option.selected {
		color: #000;
		font-weight: bold;
	}

	/* 价格筛选专属样式 */
	.price-filter-wrapper {
		display: flex;
		flex-direction: column;
		height: 100%;
	}

	.price-picker-container {
		position: relative;
		height: 480rpx;
		overflow: hidden;
	}

	/* 中间指示线 */
	.picker-indicator {
		position: absolute;
		left: 0;
		right: 0;
		top: 50%;
		transform: translateY(-50%);
		height: 70rpx;
		pointer-events: none;
		z-index: 10;
	}

	.indicator-line {
		position: absolute;
		left: 30rpx;
		right: 30rpx;
		height: 1rpx;
		background-color: #e0e0e0;
	}

	.indicator-line.top-line {
		top: 0;
	}

	.indicator-line.bottom-line {
		bottom: 0;
	}

	/* 滚动选择器 */
	.price-picker-scroll {
		height: 100%;
		width: 100%;
	}

	/* 占位元素（让第一个和最后一个元素可以滚动到中间） */
	.picker-placeholder {
		height: 205rpx;
	}

	/* 选项样式 */
	.picker-item {
		height: 70rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		color: #ccc;
		transition: all 0.2s ease;
	}

	/* 选中状态（在中间两条线之间） */
	.picker-item.picker-selected {
		color: #000;
		font-weight: bold;
		font-size: 36rpx;
	}

	/* 接近选中的项（稍微深一点的灰色） */
	.picker-item.picker-near {
		color: #999;
		font-size: 34rpx;
	}

	.filter-buttons {
		display: flex;
		align-items: center;
		height: 140rpx;
		padding: 20rpx 30rpx 30rpx;
		gap: 20rpx;
		border-top: 1rpx solid #F0F0F0;
		background-color: #fff;
	}

	.cancel-btn {
		flex: 1;
		height: 88rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
		color: #00B386;
		background-color: #fff;
		border: 2rpx solid #00B386;
		border-radius: 44rpx;
		transition: all 0.2s ease;
	}

	.cancel-btn:active {
		background-color: #F5F5F5;
	}

	.confirm-btn {
		flex: 1;
		height: 88rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
		color: #fff;
		background-color: #00B386;
		border-radius: 44rpx;
		transition: all 0.2s ease;
	}

	.confirm-btn:active {
		background-color: #009972;
	}

	/* 遮罩层 */
	.mask {
		position: fixed;
		top: 180rpx;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 996;
	}

	/* 房源列表 */
	.house-list {
		min-height: calc(100vh - 212rpx);
		background-color: #f5f5f5;
		padding-bottom: 20rpx;
	}

	.house-card {
		display: flex;
		background-color: #fff;
		margin: 20rpx 30rpx;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
	}

	.house-image {
		width: 240rpx;
		height: 180rpx;
		flex-shrink: 0;
	}

	.house-info {
		flex: 1;
		padding: 20rpx;
		display: flex;
		flex-direction: column;
	}

	.house-title {
		font-size: 30rpx;
		color: #333;
		font-weight: 500;
		margin-bottom: 10rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.house-desc {
		font-size: 24rpx;
		color: #999;
		margin-bottom: 10rpx;
	}

	.house-tags {
		display: flex;
		gap: 10rpx;
		margin-bottom: 15rpx;
	}

	.tag {
		padding: 4rpx 12rpx;
		background-color: #E6F7F3;
		color: #00B386;
		font-size: 22rpx;
		border-radius: 4rpx;
	}

	.house-footer {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.house-price {
		display: flex;
		align-items: baseline;
	}

	.price-num {
		font-size: 36rpx;
		color: #FF6B6B;
		font-weight: bold;
	}

	.price-unit {
		font-size: 24rpx;
		color: #FF6B6B;
		margin-left: 4rpx;
	}

	/* 空状态 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding-top: 200rpx;
	}

	.empty-icon {
		font-size: 120rpx;
		margin-bottom: 20rpx;
		opacity: 0.3;
	}

	.empty-text {
		font-size: 28rpx;
		color: #999;
	}

	/* 更多筛选专属样式 */
	.more-filter-wrapper {
		display: flex;
		flex-direction: column;
		height: 100%;
		background-color: #fff;
	}

	.more-filter-scroll {
		flex: 1;
		overflow-y: auto;
		padding-bottom: 20rpx;
	}

	.more-filter-title {
		text-align: center;
		font-size: 34rpx;
		font-weight: 600;
		color: #00B386;
		padding: 35rpx 0 25rpx;
		border-bottom: 1rpx solid #F5F5F5;
	}

	.filter-group {
		padding: 25rpx 30rpx;
		border-bottom: 1rpx solid #F5F5F5;
	}

	.filter-group:last-child {
		border-bottom: none;
	}

	.group-title {
		font-size: 30rpx;
		color: #00B386;
		font-weight: 600;
		margin-bottom: 25rpx;
	}

	.group-options {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 20rpx;
	}

	.option-item {
		height: 70rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		color: #666;
		background-color: #FAFAFA;
		border: 2rpx solid #E8E8E8;
		border-radius: 8rpx;
		box-sizing: border-box;
		transition: all 0.2s ease;
	}

	.option-item.option-selected {
		color: #00B386;
		background-color: #E8F7F3;
		border-color: #00B386;
		font-weight: 600;
	}
</style>